package com.czy.owner.ui.archive;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.czy.owner.R;
import com.czy.owner.adapter.ExpandableItemAdapter;
import com.czy.owner.api.OwneiInsDetailsApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.TestingDetailsModel;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.utils.TimeUtils;

import java.io.Serializable;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 车辆检测详情
 */
public class TestingDetailsActivity extends BaseActivity {


    @BindView(R.id.rv)
    RecyclerView mRecyclerView;


    @BindView(R.id.toolbar_right_title)
    TextView toolbarRightTitle;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    private ExpandableItemAdapter adapter;
    private ArrayList<MultiItemEntity> list;
    private String userOrderId, storeId;
    private TestingDetailsModel testingDetailsModel;
    private View headerView, footerView;
    private TextView tv_testing_id, tv_time, tv_car_id, tv_car_name, tv_vin, tv_store_name, tv_staff, tv_next_km_2, tv_car_next_time, tv_km;
    private LinearLayout liner_next_time, liner_next_km;
    private ImageView iv_texting_img;
    private TextView tv_note, tv_next;
    private RelativeLayout relat_next;
    private boolean abnormal;//是否有问题项
    private boolean flag;//是否查看问题项

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_testing_details;
    }

    @Override
    protected void initInjector() {
        if (getIntent() == null) {
            PhoneUtils.ShowToastMessage(TestingDetailsActivity.this, "参数异常");
            finish();
        }
        userOrderId = this.getIntent().getStringExtra("userOrderId");
        storeId = this.getIntent().getStringExtra("storeId");

    }

    @Override
    protected void initViews() {
        toolbarTitle.setText("车检详情");
        toolbarRightTitle.setText("仅查看问题项");
        toolbarRightTitle.setVisibility(View.GONE);
//        toolbarRightTitle.setTextSize(toolbarRightTitle.getTextSize() * 4 / 5);
        final LinearLayoutManager manager = new LinearLayoutManager(this);
//        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int position) {
//                return adapter.getItemViewType(position) == ExpandableItemAdapter.TYPE_PERSON ? 1 : manager.getSpanCount();
//            }
//        });
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, PhoneUtils.dip2px(this, 0.5f), this.getResources().getColor(R.color.inspection_bg)));
        mRecyclerView.setLayoutManager(manager);
        headerView = LayoutInflater.from(this).inflate(R.layout.header_expand_item, (ViewGroup) this.getWindow().getDecorView(), false);
        footerView = LayoutInflater.from(this).inflate(R.layout.footer_expand_item, (ViewGroup) this.getWindow().getDecorView(), false);
        // important! setLayoutManager should be called after setAdapter
        tv_testing_id = (TextView) headerView.findViewById(R.id.tv_testing_id);
        tv_time = (TextView) headerView.findViewById(R.id.tv_time);
        tv_car_id = (TextView) headerView.findViewById(R.id.tv_car_id);
        tv_car_name = (TextView) headerView.findViewById(R.id.tv_car_name);
        tv_vin = (TextView) headerView.findViewById(R.id.tv_vin);
        tv_km = (TextView) headerView.findViewById(R.id.tv_km);
        tv_store_name = (TextView) headerView.findViewById(R.id.tv_store_name);
        tv_staff = (TextView) headerView.findViewById(R.id.tv_staff);
        tv_car_next_time = (TextView) headerView.findViewById(R.id.tv_car_next_time);
        tv_next_km_2 = (TextView) headerView.findViewById(R.id.tv_next_km_2);
        liner_next_time = (LinearLayout) headerView.findViewById(R.id.liner_next_time);
        iv_texting_img = (ImageView) headerView.findViewById(R.id.iv_texting_img);

        liner_next_km = (LinearLayout) headerView.findViewById(R.id.liner_next_km);
        tv_note = (TextView) footerView.findViewById(R.id.tv_note);
        tv_next = (TextView) findViewById(R.id.tv_next);
        relat_next = (RelativeLayout) findViewById(R.id.relat_next);


        relat_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((testingDetailsModel.getOrderGoodsList() == null || testingDetailsModel.getOrderGoodsList().size() == 0) && (testingDetailsModel.getOrderServiceList() == null || testingDetailsModel.getOrderServiceList().size() == 0)) {
                    PhoneUtils.ShowToastMessage(TestingDetailsActivity.this, "暂无商家推荐的商品或服务");
                } else {
                    startActivity(new Intent(TestingDetailsActivity.this, TestingRecommendActivity.class)
                            .putExtra("goodsList", (Serializable) testingDetailsModel.getOrderGoodsList())
                            .putExtra("serviceList", (Serializable) testingDetailsModel.getOrderServiceList()));
                }
            }
        });
        setData();
    }

    @Override
    protected void updateViews() {

    }

    public void setAdapter() {
        list = generateData();
        if (abnormal) {
            toolbarRightTitle.setVisibility(View.VISIBLE);
        }
        if (adapter == null) {
            adapter = new ExpandableItemAdapter(list);
            mRecyclerView.setAdapter(adapter);
            adapter.addHeaderView(headerView);
            adapter.addFooterView(footerView);
        } else {
            adapter.setNewData(list);
        }
        adapter.expandAll();
//        tv_testing_id = (TextView) headerView.findViewById(R.id.tv_testing_id);
//        tv_time = (TextView) headerView.findViewById(R.id.tv_time);
//        tv_car_id = (TextView) headerView.findViewById(R.id.tv_car_id);
//        tv_car_name = (TextView) headerView.findViewById(R.id.tv_car_name);
//        tv_vin = (TextView) headerView.findViewById(R.id.tv_vin);
//        tv_km = (TextView) headerView.findViewById(R.id.tv_km);
//        tv_store_name = (TextView) headerView.findViewById(R.id.tv_store_name);
//        tv_staff = (TextView) headerView.findViewById(R.id.tv_staff);
//
//        tv_note = (TextView) footerView.findViewById(R.id.tv_note);
//        tv_next = (TextView) footerView.findViewById(R.id.tv_next);
//        relat_next = (RelativeLayout) footerView.findViewById(R.id.relat_next);
        if (testingDetailsModel.getServiceMileage() == 0) {
            liner_next_km.setVisibility(View.GONE);
        } else {
            tv_next_km_2.setText(testingDetailsModel.getServiceMileage() + "km");
            liner_next_km.setVisibility(View.VISIBLE);
        }
        if (testingDetailsModel.getServiceTime() == 0) {
            tv_car_next_time.setText("无");
            liner_next_time.setVisibility(View.GONE);
        } else {
            tv_car_next_time.setText(TimeUtils.timeStamp2Date(testingDetailsModel.getServiceTime() + "", "yyyy-MM-dd"));
            liner_next_time.setVisibility(View.VISIBLE);
        }
        tv_testing_id.setText(testingDetailsModel.getOrderNumber());
        // HH:mm:ss
        tv_time.setText(TimeUtils.timeStamp2Date(testingDetailsModel.getEndTime(), "yyyy-MM-dd"));
        tv_car_id.setText(testingDetailsModel.getLicenseNumber());
        tv_car_name.setText(testingDetailsModel.getChName());
        Glide.with(this).load(testingDetailsModel.getImageSrc()).asBitmap().centerCrop().placeholder(R.mipmap.icon_goods_list_default).into(iv_texting_img);
        if (StringUtils.isEmpty(testingDetailsModel.getChassisNumber())) {
            tv_vin.setVisibility(View.GONE);
        } else {
            tv_vin.setText("VIN码：" + testingDetailsModel.getChassisNumber());
        }
        if ((testingDetailsModel.getOrderGoodsListSize() + testingDetailsModel.getOrderServiceListSize()) != 0) {
            relat_next.setVisibility(View.VISIBLE);
        }
        tv_km.setText(testingDetailsModel.getCurrentMileage() + "km");
        tv_store_name.setText(testingDetailsModel.getStoreName());
        tv_staff.setText(testingDetailsModel.getEmployeesNames());

        tv_note.setText(StringUtils.isEmpty(testingDetailsModel.getNote()) ? "无" : testingDetailsModel.getNote());
    }

    //获取车检单详情
    public void setData() {
        OwneiInsDetailsApi owneiInsListApi = new OwneiInsDetailsApi(new HttpOnNextListener<TestingDetailsModel>() {
            @Override
            public void onNext(TestingDetailsModel o) {
                testingDetailsModel = o;
                setAdapter();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                MyLog.e("yang", "-----");

            }
        }, this);
        owneiInsListApi.setSession(UserHelper.getInstance().getSession(this));
        owneiInsListApi.setStoreId(storeId);
        owneiInsListApi.setUserOrderId(userOrderId);
        if (flag) {
            owneiInsListApi.setFlag(flag + "");
        } else {
            owneiInsListApi.setFlag("");
        }
        MyLog.e("hep", userOrderId + "-");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(owneiInsListApi);
    }

    //返回数据处理
    private ArrayList<MultiItemEntity> generateData() {
        for (int i = testingDetailsModel.getCategoryList().size() - 1; i >= 0; i--) {
            for (int j = testingDetailsModel.getCategoryList().get(i).getInspectionList().size() - 1; j >= 0; j--) {
                for (int k = testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().size() - 1; k >= 0; k--) {
                    //第四层如果为空则删除
                    for (int l = testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getItemValueList().size() - 1; l >= 0; l--) {

                        String var = testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getItemValueList().get(l).getVal();
                        testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k)
                                .setStatus(testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getItemValueList().get(l).getStatus());
                        if ("abnormal".equals(testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getStatus())) {
                            abnormal = true;
                        }
                        if (StringUtils.isEmpty(var) || "false".equals(var)) {
                            testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getItemValueList().remove(l);
                        }
                    }
                    //第三层如果为空则删除
//                    if (testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getItemValueList().size() == 0
//                            && (testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getOwnerInspectionResList() == null
//                            || testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getOwnerInspectionResList().size() == 0)) {
//                        testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().remove(k);
//                    }
                    if ("noTest".equals(testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().get(k).getStatus())) {
                        testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().remove(k);
                    }
                }
                //第二层如果为空则删除
                if (testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList() == null || testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList().size() == 0) {
                    testingDetailsModel.getCategoryList().get(i).getInspectionList().remove(j);
                }

            }
            //第一层如果为空则删除
            if (testingDetailsModel.getCategoryList().get(i).getInspectionList() == null || testingDetailsModel.getCategoryList().get(i).getInspectionList().size() == 0) {
                testingDetailsModel.getCategoryList().remove(i);
            }

        }
        for (int i = 0; i < testingDetailsModel.getCategoryList().size(); i++) {
            testingDetailsModel.getCategoryList().get(i).addAllSubItem(testingDetailsModel.getCategoryList().get(i).getInspectionList());
            for (int j = 0; j < testingDetailsModel.getCategoryList().get(i).getInspectionList().size(); j++) {
                testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).addAllSubItem(testingDetailsModel.getCategoryList().get(i).getInspectionList().get(j).getItemList());
            }
        }

        ArrayList<MultiItemEntity> res = new ArrayList<>();
        res.addAll(testingDetailsModel.getCategoryList());
//        for (int i = 0; i < lv0Count; i++) {
//            Level0Item lv0 = new Level0Item(name[i] + i + "", "" + i);
//            for (int j = 0; j < lv1Count; j++) {
//                Level1Item lv1 = new Level1Item(name2[j] + j, "(no animation)");
//                for (int k = 0; k < personCount; k++) {
//                    Person person = new Person(nameList[k], random.nextInt(40));
//                    person.setList(listType);
//                    lv1.addSubItem(person);
//                }
//                lv0.addSubItem(lv1);
//            }
//            res.add(lv0);
//        }

        return res;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.linear_right_text, R.id.tv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.linear_right_text:
                flag = !flag;
                if (flag) {
                    toolbarRightTitle.setText("查看完整车检");
                } else {
                    toolbarRightTitle.setText("仅查看问题项");
                }
                setData();
                break;
            case R.id.tv_next:
                break;
        }
    }
}
